﻿using AutoMapper;
using MediatR;
using Traceability.App.Api.Application.Command.Add;
using Traceability.App.Domain;
using Traceability.App.ErrorCode;
using Traceability.App.Instructure;

namespace Traceability.App.Api.Application.Handler.Add
{
    /// <summary>
    /// 修改养殖企业信息
    /// </summary>
    public class UpdateYangCompanyHandler : IRequestHandler<UpdateYangCompanyCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<AquaculturefarmCompanyModel> aquacultureRepo;
        private readonly IMapper mapper;

        public UpdateYangCompanyHandler(IBaseRepository<AquaculturefarmCompanyModel> aquacultureRepo,IMapper mapper) 
        {
            this.aquacultureRepo = aquacultureRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateYangCompanyCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var aqcompany = aquacultureRepo.GetAll().Where(x => x.Batch == request.Batch).FirstOrDefault();
            if (aqcompany==null)
            {
                var entity = mapper.Map<AquaculturefarmCompanyModel>(request);
                aquacultureRepo.Add(entity);
            }
            else
            {
                aqcompany.Cnumber= request.Cnumber;
                aqcompany.YangName= request.YangName;
                aqcompany.HeadName= request.HeadName;
                aqcompany.UpdateName = "张三";
                aqcompany.CreateName = "张三";
                aqcompany.UpdateTime = DateTime.Now;
                aqcompany.CreateTime = DateTime.Now;
                aquacultureRepo.Update(aqcompany);
            }
            res.Code = ApiEnum.Success;
            res.Msg = "修改养殖场企业成功";
            return Task.FromResult(res);
        }
    }
}
